<template>
  <view class="login-dialog" v-if="visible">
    <view class="mask" @click="handleClickMask"></view>
    <view class="content">
      <!-- 顶部关闭按钮 -->
      <view class="close-btn" @click="handleClose">
        <text class="tn-icon-close"></text>
      </view>
      
      <!-- 登录标题 -->
      <view class="dialog-title">
        <text>{{ currentTab === 'code' ? '手机验证码登录' : '手机号登录' }}</text>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-area">
        <!-- 手机号输入 -->
        <view class="form-item">
          <view class="input-wrapper">
            <text class="tn-icon-mobile"></text>
            <input 
              type="number" 
              v-model="formData.mobile" 
              placeholder="请输入手机号"
              maxlength="11"
              @input="validateMobile"
            />
          </view>
          <view class="error-msg" v-if="errors.mobile">{{ errors.mobile }}</view>
        </view>
        
        <!-- 验证码输入 -->
        <view class="form-item" v-if="currentTab === 'code'">
          <view class="input-wrapper">
            <text class="tn-icon-safe"></text>
            <input 
              type="number" 
              v-model="formData.code" 
              placeholder="请输入验证码"
              maxlength="6"
              @input="validateCode"
            />
            <view 
              class="code-btn" 
              :class="{ 'disabled': countdown > 0 }"
              @click="handleSendCode"
            >
              <text>{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}</text>
            </view>
          </view>
          <view class="error-msg" v-if="errors.code">{{ errors.code }}</view>
        </view>
        
        <!-- 密码输入 -->
        <view class="form-item" v-if="currentTab === 'password'">
          <view class="input-wrapper">
            <text class="tn-icon-lock"></text>
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="formData.password" 
              placeholder="请输入密码"
              @input="validatePassword"
            />
            <text 
              class="tn-icon-eye" 
              v-if="showPassword" 
              @click="showPassword = false"
            ></text>
            <text 
              class="tn-icon-eye-hide" 
              v-else 
              @click="showPassword = true"
            ></text>
          </view>
          <view class="error-msg" v-if="errors.password">{{ errors.password }}</view>
        </view>
        
        <!-- 登录按钮 -->
        <view class="login-btn-wrapper">
          <button 
            class="login-btn" 
            :disabled="!isFormValid" 
            :class="{ 'disabled': !isFormValid }"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </view>
        
        <!-- 切换登录方式 -->
        <view class="switch-login-type" @click="switchLoginType">
          <text>{{ currentTab === 'code' ? '使用密码登录' : '使用验证码登录' }}</text>
        </view>
        
        <!-- 协议 -->
        <view class="agreement">
          <view class="checkbox" @click="agreed = !agreed">
            <view class="checkbox-inner" :class="{ 'checked': agreed }"></view>
          </view>
          <view class="agreement-text">
            我已阅读并同意
            <text class="link" @click.stop="handleViewPrivacy">《隐私政策》</text>
            和
            <text class="link" @click.stop="handleViewTerms">《用户协议》</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import API from '@/api/index.js';
import { setToken } from '@/utils/auth.js'; // 导入setToken方法

export default {
  name: 'LoginDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentTab: 'code', // 'code'-验证码登录, 'password'-密码登录
      formData: {
        mobile: '',
        code: '',
        password: ''
      },
      errors: {
        mobile: '',
        code: '',
        password: ''
      },
      countdown: 0,
      timer: null,
      agreed: true,
      showPassword: false,
      loading: false
    };
  },
  computed: {
    isFormValid() {
      if (!this.agreed) return false;
      if (!this.formData.mobile || this.errors.mobile) return false;
      
      if (this.currentTab === 'code') {
        return !!this.formData.code && !this.errors.code;
      } else {
        return !!this.formData.password && !this.errors.password;
      }
    }
  },
  methods: {
    ...mapMutations('user', [
      'SET_USER_INFO',
      'SET_TOKEN_INFO',
      'SET_LOGIN_STATUS'
    ]),
    ...mapMutations('app', [
      'SET_LOGIN_VISIBLE'
    ]),
    ...mapActions('user', [
      'getUserInfo'
    ]),
    
    // 切换登录方式
    switchLoginType() {
      this.currentTab = this.currentTab === 'code' ? 'password' : 'code';
      // 重置错误信息
      this.errors = {
        mobile: '',
        code: '',
        password: ''
      };
    },
    
    // 手机号验证
    validateMobile() {
      if (!this.formData.mobile) {
        this.errors.mobile = '请输入手机号';
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.mobile)) {
        this.errors.mobile = '手机号格式不正确';
        return false;
      }
      this.errors.mobile = '';
      return true;
    },
    
    // 验证码验证
    validateCode() {
      if (!this.formData.code) {
        this.errors.code = '请输入验证码';
        return false;
      }
      if (!/^\d{4,6}$/.test(this.formData.code)) {
        this.errors.code = '验证码格式不正确';
        return false;
      }
      this.errors.code = '';
      return true;
    },
    
    // 密码验证
    validatePassword() {
      if (!this.formData.password) {
        this.errors.password = '请输入密码';
        return false;
      }
      if (this.formData.password.length < 6) {
        this.errors.password = '密码长度不能少于6位';
        return false;
      }
      this.errors.password = '';
      return true;
    },
    
    // 发送验证码
    async handleSendCode() {
      if (this.countdown > 0) return;
      
      if (!this.validateMobile()) return;
      
      try {
        uni.showLoading({
          title: '发送中...'
        });
        
        // 调用发送验证码接口
        await API.user.sendSmsCode({
          mobile: this.formData.mobile,
          scene: 1 // 登录场景
        });
        
        // 开始倒计时
        this.countdown = 60;
        this.timer = setInterval(() => {
          this.countdown--;
          if (this.countdown <= 0) {
            clearInterval(this.timer);
          }
        }, 1000);
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'none'
        });
      } catch (error) {
        console.error('发送验证码失败:', error);
        uni.showToast({
          title: error.message || '发送验证码失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 登录
    async handleLogin() {
      if (this.loading || !this.isFormValid) return;
      
      if (!this.agreed) {
        uni.showToast({
          title: '请阅读并同意用户协议和隐私政策',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      try {
        uni.showLoading({
          title: '登录中...'
        });
        
        let result;
        if (this.currentTab === 'code') {
          // 验证码登录
          result = await API.user.smsLogin({
            mobile: this.formData.mobile,
            code: this.formData.code
          });
        } else {
          // 密码登录
          result = await API.user.passwordLogin({
            mobile: this.formData.mobile,
            password: this.formData.password
          });
        }
        
        // 获取token数据
        const tokenData = result.data || result;
        
        // 保存token信息到Vuex
        this.SET_TOKEN_INFO(tokenData);
        
        // 显式调用setToken确保token存储到localStorage
        setToken(tokenData);
        
        // 设置登录状态
        this.SET_LOGIN_STATUS(true);
        
        // 获取用户信息
        await this.getUserInfo();
        
        // 触发登录成功回调
        this.$store.dispatch('user/handleLoginSuccess');
        
        // 关闭登录弹窗
        this.handleClose();
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });
      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },
    
    // 关闭弹窗
    handleClose() {
      this.SET_LOGIN_VISIBLE(false);
    },
    
    // 点击遮罩层
    handleClickMask() {
      // 不允许点击遮罩关闭
    },
    
    // 查看隐私政策
    handleViewPrivacy() {
      // 跳转到隐私政策页面
      uni.navigateTo({
        url: '/pages/common/privacy/privacy'
      });
    },
    
    // 查看用户协议
    handleViewTerms() {
      // 跳转到用户协议页面
      uni.navigateTo({
        url: '/pages/common/terms/terms'
      });
    }
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
}
</script>

<style lang="scss" scoped>
.login-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  
  .mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
  }
  
  .content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding: 40rpx;
    padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
    
    .close-btn {
      position: absolute;
      top: 30rpx;
      right: 30rpx;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .tn-icon-close {
        font-size: 40rpx;
        color: #666;
      }
    }
    
    .dialog-title {
      font-size: 36rpx;
      font-weight: bold;
      margin-top: 20rpx;
      margin-bottom: 60rpx;
      text-align: center;
    }
    
    .form-area {
      .form-item {
        margin-bottom: 40rpx;
        
        .input-wrapper {
          display: flex;
          align-items: center;
          border-bottom: 1px solid #eee;
          padding: 20rpx 0;
          
          text {
            font-size: 40rpx;
            color: #333;
            margin-right: 20rpx;
          }
          
          input {
            flex: 1;
            height: 60rpx;
            font-size: 32rpx;
          }
          
          .code-btn {
            padding: 10rpx 20rpx;
            background-color: #B3F73C;
            border-radius: 30rpx;
            
            text {
              font-size: 24rpx;
              color: #333;
              margin: 0;
            }
            
            &.disabled {
              background-color: #eee;
            }
          }
        }
        
        .error-msg {
          font-size: 24rpx;
          color: #ff4d4f;
          margin-top: 10rpx;
          padding-left: 60rpx;
        }
      }
      
      .login-btn-wrapper {
        margin-top: 60rpx;
        
        .login-btn {
          width: 100%;
          height: 90rpx;
          line-height: 90rpx;
          text-align: center;
          background-color: #B3F73C;
          color: #333;
          font-size: 32rpx;
          font-weight: bold;
          border-radius: 45rpx;
          
          &.disabled {
            background-color: #eee;
            color: #999;
          }
        }
      }
      
      .switch-login-type {
        margin-top: 30rpx;
        text-align: center;
        
        text {
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .agreement {
        margin-top: 40rpx;
        display: flex;
        align-items: center;
        
        .checkbox {
          width: 40rpx;
          height: 40rpx;
          border: 1px solid #ddd;
          border-radius: 6rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
          
          .checkbox-inner {
            width: 30rpx;
            height: 30rpx;
            border-radius: 4rpx;
            
            &.checked {
              background-color: #B3F73C;
            }
          }
        }
        
        .agreement-text {
          font-size: 24rpx;
          color: #666;
          
          .link {
            color: #B3F73C;
          }
        }
      }
    }
  }
}
</style> 